//
//  JianXiViewController.m
//  jingjing2.0
//
//  Created by apple on 16/5/4.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "JianXiViewController.h"
#import "JianXiTableViewCell.h"
#import "JianXiData.h"
#import "Header.h"
#import "CartView.h"
#import "SubmitOrderViewController.h"
@interface JianXiViewController ()<UITableViewDelegate,UITableViewDataSource,MethodToAddBtnDelegate,UIScrollViewDelegate>

{
      CALayer     *_layer;
   UIButton    *_btn;//购物车按钮
    UILabel *_sum;//总价
    CGFloat _sumPrice;
    UIButton *_sureBtn;//选好了
    UIScrollView *_scrollView;
    UISegmentedControl *_seg;
    NSMutableArray *_shoppingCartArr;//洗衣篮子
    UIView *_bgView;//遮罩层
}
@property (nonatomic,strong) UIBezierPath *path;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,strong)CartView *cartView;
@end

@implementation JianXiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNav];
    
   
    _cnt=0;
    _sumPrice=0;
    _shoppingCartArr=[NSMutableArray array];
    [self setUpScrollView];
    [self setUpTableView];
    [self setUpBlackView];
    [self setUpCartView];
    [self setUpBottomView];
    [self beginRefresh];
}
#pragma mark--创建遮罩层
-(void)setUpBlackView
{
    _bgView=[[UIView alloc]initWithFrame:self.view.frame];
    _bgView.backgroundColor=[UIColor blackColor];
    _bgView.alpha=0.5;
    _bgView.hidden=YES;
    [_scrollView addSubview:_bgView];
}
#pragma mark--创建滑动视图
-(void)setUpScrollView
{
    _scrollView=[[UIScrollView alloc]init];
    _scrollView.frame=CGRectMake(0, 0, kWidth, kHeight);
    _scrollView.contentSize=CGSizeMake(kWidth*2, 0);
    _scrollView.pagingEnabled=YES;
    _scrollView.delegate=self;
    _scrollView.showsHorizontalScrollIndicator=NO;
    _scrollView.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:_scrollView];
}
#pragma mark--创建表
-(void)setUpTableView
{
    if (!_dataSource)
    {
        _dataSource = [NSMutableArray array];
    }
    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, kWidth, kHeight-64-50) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.rowHeight=130;
    [_tableView registerNib:[UINib nibWithNibName:@"JianXiTableViewCell" bundle:nil] forCellReuseIdentifier:@"JianXi"];
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTheTableView)];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeNumber:) name:@"RowChange" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changePrice:) name:@"PriceChange" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(clearCart) name:@"ClearCart" object:nil];
    
    [_scrollView addSubview:_tableView];
}
#pragma mark--改变价格和总数
-(void)clearCart
{
//    [_shoppingCartArr removeAllObjects];
    [self cartViewDownWithHeight:0];
    [self reduce];
    [self beginRefresh];
}
-(void)changePrice:(NSNotification *)info
{
    NSDictionary *dic=info.object;
    NSArray *keys=[dic allKeys];
    for (NSString *count in keys) {
        _cnt=[count intValue];
        _cntLabel.text=count;
        NSString *sumPrice=[NSString stringWithFormat:@"共计：￥%@",dic[count]];//价格保留一位小数
        NSInteger length=[dic[count] length];
        NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:sumPrice];
        //把价格的字体颜色变为红色
        [attriString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3, length+1)];
        [_sum setAttributedText:attriString];
        
    }
}
#pragma mark--改变件数
-(void)changeNumber:(NSNotification *)info
{
    NSDictionary *dic=info.object;
    NSArray *keys=[dic allKeys];
 
    for (NSString *title in keys) {
            [self.dataSource enumerateObjectsUsingBlock:^(JianXiData *data, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([[data.ProOrderCategoryName stringByRemovingPercentEncoding] isEqualToString:title])
            {
                NSInteger index=[self.dataSource indexOfObject:data];
                NSIndexPath *indexPath=[NSIndexPath indexPathForRow:index inSection:0];
                JianXiTableViewCell *cell=[_tableView cellForRowAtIndexPath:indexPath];
                if ([dic[title]integerValue]==0) {
                    cell.minBtn.hidden=YES;
                    cell.numberCount.hidden=YES;
                }else
                {
                    cell.numberCount.text=[dic objectForKey:title];
                };
                
            }
        }];
    }
    
}
#pragma mark--创建介绍视图
-(void)setUpIntroduceViewWithArr:(NSMutableArray *)arr
{
    if (!_introduceView) {
         _introduceView=[[IntrodeceView alloc]initWithArr:arr andFrame:CGRectMake(kWidth, 64, kWidth, kHeight-64)];
        [_scrollView addSubview:_introduceView];

    }
}
#pragma mark--刷新表数据
-(void)beginRefresh
{
    [_tableView.mj_header beginRefreshing];
}
-(void)refreshTheTableView
{
    [_dataSource removeAllObjects];
    //请求数据
    [self getJianXiData];
    
}
-(void)getJianXiData
{
    NSString *CategoryID=[NSString stringWithFormat:@"%zd",self.categoryID];
    NSString *timestamp=[GeneralTool gettimestamp];
    NSDictionary *dic=@{@"CategoryID":CategoryID,@"Timestamp":timestamp};
    NSString *sign=[GeneralTool GetSin:dic];
    NSString *urlString=[NSString stringWithFormat:@"Product/ProCatList/%@/%@/%@",CategoryID,timestamp,sign];
    [RequestTool requestDataWithType:@"get" andUrlString:urlString andParameters:nil andRequestFinished:^(id responses, NSError *error)
     {
         if (error) {
             [MBProgressHUD showError:@"刷新失败，请检查网络"];
             
         }else
         {
             if ([responses[@"IsSuccess"]intValue]==1) {
                 
                 NSArray *arr=responses[@"ReturnObject"];
                 [arr enumerateObjectsUsingBlock:^(NSDictionary  * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                     JianXiData *JianXi=[[JianXiData alloc]initWithDic:obj];
                     [self.dataSource addObject:JianXi];
                 }];
                 if (self.dataSource.count!=0) {
                     [self setUpIntroduceViewWithArr:self.dataSource];
                 }
                
                 [_tableView reloadData];
             }
         }
         [_tableView.mj_header endRefreshing];
    }];
    
}
#pragma mrak--滑动视图代理方法
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    _seg.selectedSegmentIndex=scrollView.contentOffset.x/kWidth;
}
#pragma mark--表代理方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JianXiTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"JianXi" forIndexPath:indexPath];
    cell.delegate=self;
    
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    JianXiData *data=self.dataSource[indexPath.row];
    cell.addBtn.title=[data.ProOrderCategoryName stringByRemovingPercentEncoding];
    cell.minBtn.title=[data.ProOrderCategoryName stringByRemovingPercentEncoding];
    [cell.headImage sd_setImageWithURL:[NSURL URLWithString:data.ImgUrl]];
    cell.numberCount.hidden=YES;
    cell.minBtn.hidden=YES;
    cell.title.text=[data.ProOrderCategoryName stringByRemovingPercentEncoding];
    cell.introduce.text=[data.ProNames stringByRemovingPercentEncoding];
    cell.price.text=[NSString stringWithFormat:@"￥%@元/%@",data.Price,data.ComputeUnitName];
    cell.addBtn.price=[data.Price floatValue];//记录价格
    cell.minBtn.price=[data.Price floatValue];//记录价格
    cell.remark.text=[data.Remark stringByRemovingPercentEncoding];
    
    //衣物加入购物车动画
    typeof(self) weakSelf=self;
    typeof(self.tableView) weakTableView=self.tableView;
    cell.shopCartBlock = ^(UIImageView *imageView){
                 CGRect rect = [tableView rectForRowAtIndexPath:indexPath];
                rect.origin.y = rect.origin.y - [weakTableView contentOffset].y;
                CGRect headRect = imageView.frame;
                headRect.origin.y = rect.origin.y+headRect.origin.y;
                [weakSelf startAnimationWithRect:headRect ImageView:imageView];
            };

    return cell;
}
#pragma mark--实现cell的代理方法
-(void)doThingsOnControllerForView:(CustomButton *)btn withType:(BOOL)isAdd
{

    /* 加减号两个按钮都有对应的属性记录对方*/
    CustomButton *button=btn.btn;
    UILabel *label=btn.label;
    if (btn.label.hidden==YES) {
        [self add];//增加操作
        btn.number=1;//赋初始值
        button.number=1;//初始值保持一致
        _sumPrice+=btn.number*btn.price;
        button.hidden=NO;
        label.hidden=NO;
        _btn.enabled=YES;
        _sureBtn.enabled=YES;
        [_shoppingCartArr addObject:btn];

    }else
    {
        if (isAdd) {
            btn.number++;//加号上记录个数加1
            if (btn.number>=99) {
                return;
            }
            button.number=btn.number;//减号上的记录个数应该保持一致
            _sumPrice+=btn.price;//计算价格
            if ([_shoppingCartArr containsObject:btn]) {
                NSUInteger index=[_shoppingCartArr indexOfObject:btn];
                [_shoppingCartArr removeObjectAtIndex:index];
                [_shoppingCartArr addObject:btn];
            }
        }else
        {
            btn.number--;//减号上记录的个数减1
            button.number=btn.number;//加号上的记录个数保持一致
            _sumPrice-=btn.price;
            if ([_shoppingCartArr containsObject:button]) {
                NSUInteger index=[_shoppingCartArr indexOfObject:button];
                if (btn.number>=1) {
                    [_shoppingCartArr replaceObjectAtIndex:index withObject:button];
                }else
                {
                    [_shoppingCartArr removeObject:button];
                }
            }
           _cnt--;//购物车记录个数相应减小
            if (_cnt<1)
            {
                _cntLabel.hidden = YES;
            }else
            {
                [self reduceProductsAnimations];//物品减少时购物车动画
            }
        }
        if (btn.number<1) {
            btn.number=0;
            btn.hidden=YES;
            label.hidden=YES;
        }
    }
    if (_sumPrice<=0) {
        _sumPrice=0;//当价格小于零防止为负数
        [self reduce];
    }else
    {
        NSString *sumPrice=[NSString stringWithFormat:@"共计：￥%.1f",_sumPrice];//价格保留一位小数
        NSInteger length=[NSString stringWithFormat:@"%.1f",_sumPrice].length;
        NSMutableAttributedString *attriString = [[NSMutableAttributedString alloc] initWithString:sumPrice];
        
        //把价格的字体颜色变为红色
        [attriString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(3, length+1)];
        [_sum setAttributedText:attriString];
        label.text=[NSString stringWithFormat:@"%zd",button.number];
    }

}
#pragma mark--购物车动画
-(void)startAnimationWithRect:(CGRect)rect ImageView:(UIImageView *)imageView
{
    if (!_layer) {
        _layer = [CALayer layer];
        _layer.contents = (id)imageView.layer.contents;
        _layer.contentsGravity = kCAGravityResizeAspectFill;
        _layer.bounds = rect;
        [_layer setCornerRadius:CGRectGetHeight([_layer bounds]) / 2];
        _layer.masksToBounds = YES;
        // 导航64
        _layer.position = CGPointMake(imageView.center.x, CGRectGetMidY(rect)+64);
        [self.view.layer addSublayer:_layer];
        self.path = [UIBezierPath bezierPath];
        [_path moveToPoint:_layer.position];
        [_path addQuadCurveToPoint:CGPointMake(40, kHeight-40) controlPoint:CGPointMake(kWidth/2,rect.origin.y+50)];
    }
    [self groupAnimation];
}
//添加物品动画组
-(void)groupAnimation
{
    _tableView.userInteractionEnabled = NO;
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = _path.CGPath;
    animation.rotationMode = kCAAnimationRotateAuto;
    CABasicAnimation *expandAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    expandAnimation.duration = 0.3f;
    expandAnimation.fromValue = [NSNumber numberWithFloat:1];
    expandAnimation.toValue = [NSNumber numberWithFloat:2.0f];
    expandAnimation.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
    
    CABasicAnimation *narrowAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    narrowAnimation.beginTime = 0.3;
    narrowAnimation.fromValue = [NSNumber numberWithFloat:2.0f];
    narrowAnimation.duration = 1.0f;
    narrowAnimation.toValue = [NSNumber numberWithFloat:0.3f];
    
    narrowAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    
    CAAnimationGroup *groups = [CAAnimationGroup animation];
    groups.animations = @[animation,expandAnimation,narrowAnimation];
    groups.duration = 1.0f;
    groups.removedOnCompletion=NO;
    groups.fillMode=kCAFillModeForwards;
    groups.delegate = self;
    [_layer addAnimation:groups forKey:@"group"];
}

//购物车增加物品动画
-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    if (anim == [_layer animationForKey:@"group"]) {
        _tableView.userInteractionEnabled = YES;
        [_layer removeFromSuperlayer];
        _layer = nil;
        _cnt++;
        if (_cnt) {
            _cntLabel.hidden = NO;
        }
         _cntLabel.text = [NSString stringWithFormat:@"%zd",_cnt];
        CATransition *animation = [CATransition animation];
        animation.duration = 0.25f;
       
        [_cntLabel.layer addAnimation:animation forKey:nil];
        CABasicAnimation *shakeAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
        shakeAnimation.duration = 0.25f;
        shakeAnimation.fromValue = [NSNumber numberWithFloat:-5];
        shakeAnimation.toValue = [NSNumber numberWithFloat:5];
        shakeAnimation.autoreverses = YES;
        [_btn.layer addAnimation:shakeAnimation forKey:nil];
    }
}
//购物车减少物品动画
-(void)reduceProductsAnimations
{
    CATransition *animation = [CATransition animation];
    animation.duration = 0.25f;
    
    [_cntLabel.layer addAnimation:animation forKey:nil];
    CABasicAnimation *shakeAnimation = [CABasicAnimation animationWithKeyPath:@"transform.translation.x"];
    shakeAnimation.duration = 0.25f;
    shakeAnimation.fromValue = [NSNumber numberWithFloat:-5];
    shakeAnimation.toValue = [NSNumber numberWithFloat:5];
    shakeAnimation.autoreverses = YES;
    [_btn.layer addAnimation:shakeAnimation forKey:nil];
    _cntLabel.text = [NSString stringWithFormat:@"%zd",_cnt];
}
//增加数量时的操作
-(void)add
{
    [_btn setImage:[UIImage imageNamed:@"HaveTabCartSelected@2x"] forState:UIControlStateNormal];
    _sureBtn.backgroundColor=BLUECOLOR;
    _sureBtn.enabled=YES;
    _btn.enabled=YES;
}
//减少操作
-(void)reduce
{
    [_btn setImage:[UIImage imageNamed:@"TabCartSelected@2x"] forState:UIControlStateNormal];
    _sum.text=@"您还未添加任何衣物哦～";
    _sureBtn.backgroundColor=GRAYCOLOR;
    _sureBtn.enabled=NO;
    _btn.enabled=NO;
    _cnt=0;
    _sumPrice=0;
    _cntLabel.hidden=YES;
}
//购物车清单动画
-(void)cartViewDownWithHeight:(CGFloat)height
{
    _bgView.hidden=YES;
    _btn.selected=NO;
    [UIView animateWithDuration:0.5 animations:^{
        _cartView.frame=CGRectMake(0, kHeight, kWidth, height);
    }];

}
-(void)cartViewUpWithHeight:(CGFloat)height
{
    _bgView.hidden=NO;
     _cartView.hidden=NO;
    [UIView animateWithDuration:0.5 animations:^{
        _cartView.frame=CGRectMake(0, kHeight-height-50, kWidth, height);
    }];
    
}
#pragma mark--创建底部购物车
-(void)setUpBottomView
{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, kHeight-50, kWidth, 50)];
    view.backgroundColor=[UIColor colorWithRed:217/255.0 green:217/255.0 blue:217/255.0 alpha:0.5];
    [_scrollView addSubview:view];
   
    //购物车
    _btn = [[UIButton alloc] initWithFrame:CGRectMake(view.frame.origin.x+10, view.frame.origin.y-10, 50, 50)];
    [_btn setImage:[UIImage imageNamed:@"TabCartSelected@2x"] forState:UIControlStateNormal];
    [_btn addTarget:self action:@selector(clickOnShoppingCart) forControlEvents:UIControlEventTouchUpInside];
    _btn.enabled=NO;
    _sureBtn.enabled=NO;
    [_scrollView addSubview:_btn];
    //计数
    _cntLabel = [[UILabel alloc] initWithFrame:CGRectMake((_btn.frame.origin.x+40), _btn.frame.origin.y-5, 20, 20)];
    _cntLabel.textColor = [UIColor whiteColor];
    _cntLabel.textAlignment = NSTextAlignmentCenter;
    _cntLabel.font = [UIFont boldSystemFontOfSize:11];
    _cntLabel.backgroundColor = [UIColor whiteColor];
    _cntLabel.layer.cornerRadius = CGRectGetHeight(_cntLabel.bounds)/2;
    _cntLabel.layer.masksToBounds = YES;
    _cntLabel.backgroundColor=[UIColor redColor];
    [_scrollView addSubview:_cntLabel];
    if (_cnt == 0) {
        _cntLabel.hidden = YES;
    }
    //总价
    _sum=[[UILabel alloc]initWithFrame:CGRectMake(_btn.frame.origin.x+30+30,view.frame.origin.y +10, 160, 30)];
    _sum.text=@"您还未添加任何衣物哦～";
    _sum.font=[UIFont systemFontOfSize:13];
    [_scrollView addSubview:_sum];

   //选好了
    _sureBtn=[[UIButton alloc]initWithFrame:CGRectMake(kWidth-10-80, view.frame.origin.y+10, 80, 30)];
    [_sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_sureBtn setTitle:@"选好了" forState:UIControlStateNormal];
    _sureBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    _sureBtn.backgroundColor=[UIColor colorWithRed:217/255.0 green:217/255.0 blue:217/255.0 alpha:0.8];
    _sureBtn.layer.cornerRadius=3;
    _sureBtn.clipsToBounds=YES;
    [_sureBtn addTarget:self action:@selector(clickOnSure) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:_sureBtn];
}
//购物车详情
-(void)clickOnShoppingCart
{
    CGFloat height=(_shoppingCartArr.count+1)*50;
 
    _cartView.sumPrice=_sumPrice;
    _cartView.count=_cnt;
    _cartView.dataSource=_shoppingCartArr;
    [_cartView.tableView reloadData];
   
    [[NSNotificationCenter defaultCenter]postNotificationName:@"changeFrame" object:@(height)];
    
    if (_btn.selected==NO) {
        [self cartViewUpWithHeight:height];
        _btn.selected=YES;
    }else
    {
        [self cartViewDownWithHeight:height];
       _btn.selected=NO;
    }
   
}
//选好了
-(void)clickOnSure
{
    SubmitOrderViewController *submitOrder=[[SubmitOrderViewController alloc]init];
    submitOrder.price=_sumPrice;
    submitOrder.dataSource=_shoppingCartArr;
    submitOrder.categoryID=[NSString stringWithFormat:@"%zd",_categoryID];
    submitOrder.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:submitOrder animated:YES];
}
#pragma mark--净净洗衣篮子
-(void)setUpCartView
{
    if (!_cartView) {
        _cartView=[[CartView  alloc]initWithFrame:CGRectMake(0, kHeight, kWidth, 0)] ;
        _cartView.hidden=YES;
        _cartView.delegate=self;
        [_scrollView addSubview:_cartView];
    }
}
#pragma mark--导航
-(void)setUpNav
{
    self.automaticallyAdjustsScrollViewInsets=NO;
    self.view.backgroundColor=[UIColor whiteColor];
   _seg=[[UISegmentedControl alloc]initWithItems:@[@"按件洗",@"介绍"]];
    _seg.selectedSegmentIndex=0;
    [_seg addTarget:self action:@selector(clickOnSegMent:) forControlEvents:UIControlEventValueChanged];
    self.navigationItem.titleView=_seg;
}
-(void)clickOnSegMent:(UISegmentedControl *)seg
{
    if (seg.selectedSegmentIndex==0) {
        [_scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    }else
    {
        [_scrollView setContentOffset:CGPointMake(kWidth, 0) animated:YES];
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [GeneralTool hideTabBar];
   
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [GeneralTool showTabBar];
    [self cartViewDownWithHeight:0];
}
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
